package com.scx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.scx.constant.StatusConstant;
import com.scx.context.BaseContext;
import com.scx.entity.AddressBook;
import com.scx.mapper.AddressBookMapper;
import com.scx.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    AddressBookMapper addressBookMapper;

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        return addressBookMapper.selectList(queryWrapper);
    }

    @Override
    public AddressBook getById(Long id) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getId,id);
        return addressBookMapper.selectOne(queryWrapper);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault,StatusConstant.ENABLE);
        return addressBookMapper.selectOne(queryWrapper);
    }

    @Override
    public void setDefault(AddressBook addressBook) {
        //将其余地址设为非默认
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
        luw.eq(AddressBook::getUserId,BaseContext.getCurrentId())
                .set(AddressBook::getIsDefault,StatusConstant.DISABLE);
        addressBookMapper.update(addressBook,luw);
        //设置为默认
        LambdaUpdateWrapper<AddressBook> luw1 = new LambdaUpdateWrapper<>();
        luw1.eq(AddressBook::getId,addressBook.getId())
                .set(AddressBook::getIsDefault,StatusConstant.ENABLE);
        addressBookMapper.update(addressBook,luw1);
    }


}
